package com.lollipop.synthential.interceptor;

import com.lollipop.synthential.annotation.AccessLimit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: J.K
 * @Date: 2021-02-24 18:10
 * @Description:
 */
@Slf4j
public class AntiBrushInterceptor implements HandlerInterceptor {

    Map<String, Integer> conMap = new ConcurrentHashMap<String, Integer>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断请求是否属于方法的请求
        if (handler instanceof HandlerMethod) {

            HandlerMethod hm = (HandlerMethod) handler;

            //获取方法中的注解,看是否有该注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) {
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean login = accessLimit.needLogin();

            String key = request.getRequestURI();
            //如果需要登录
            if (login) {
                //获取登录的session进行判断
                //.....
                key += "" + "1";
            }

            Integer count = conMap.get("count");

            if (count == null) {
                //第一次访问
                log.info("第{}次访问", 1);
                conMap.put("count", 1);
            } else if (count < maxCount) {

                log.info("第{}次访问", count);
                conMap.put("count", count);
            } else {
                //超出访问次数

                return false;
            }
        }

        return true;
    }
}
